<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="楼宇ID" prop="userBuildingId">-->
<!--        <el-input-->
<!--          v-model="queryParams.userBuildingId"-->
<!--          placeholder="请输入楼宇ID"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="房屋ID" prop="userRoomId">-->
<!--        <el-input-->
<!--          v-model="queryParams.userRoomId"-->
<!--          placeholder="请输入房屋ID"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="审核状态" prop="reviewStatus">
        <el-select
          v-model="queryParams.reviewStatus"
          placeholder="请选择审核状态"
          clearable
          @change="handleQuery"
        >
          <el-option label="未审核" value="1" />
          <el-option label="审核通过" value="0" />
          <el-option label="审核未通过" value="2" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="业主ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入业主ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="Plus"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['auditUserDetail:reviewUserDetail:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Check"
          :disabled="single"
          @click="handleApproval"
          v-hasPermi="['auditUserDetail:reviewUserDetail:approval']"
        >审核通过</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['auditUserDetail:reviewUserDetail:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['auditUserDetail:reviewUserDetail:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reviewUserDetailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="楼宇名称" align="center">
        <template #default="scope">
          {{ getBuildingName(scope.row.userBuildingId) }}
        </template>
      </el-table-column>
      <el-table-column label="房间号" align="center">
        <template #default="scope">
          {{ getRoomNo(scope.row.userRoomId) }}
        </template>
      </el-table-column>
      <el-table-column label="用户车牌" align="center" prop="userCarCode" />
      <!-- <el-table-column label="特征数据" align="center" prop="userFaceFeature" /> -->
      <el-table-column label="业主姓名" align="center">
        <template #default="scope">
          {{ getUserName(scope.row.userId) }}
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.reviewStatus === 1" type="info">待审核</el-tag>
          <el-tag v-if="scope.row.reviewStatus === 0" type="success">审核通过</el-tag>
          <el-tag v-if="scope.row.reviewStatus === 2" type="danger">审核未通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            v-if="scope.row.reviewStatus !== 0" 
            link 
            type="primary" 
            icon="Check" 
            @click="handleApproval(scope.row)" 
            v-hasPermi="['auditUserDetail:reviewUserDetail:edit']"
            :disabled="approvalButtonDisabled[scope.row.id]">
            {{ approvalButtonDisabled[scope.row.id] ? '审核中...' : '审核通过' }}
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['auditUserDetail:reviewUserDetail:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改业主绑定信息审核对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="reviewUserDetailRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼宇ID" prop="userBuildingId">
          <el-input v-model="form.userBuildingId" placeholder="请输入楼宇ID" />
        </el-form-item>
        <el-form-item label="房屋ID" prop="userRoomId">
          <el-input v-model="form.userRoomId" placeholder="请输入房屋ID" />
        </el-form-item>
        <el-form-item label="用户车牌" prop="userCarCode">
          <el-input v-model="form.userCarCode" placeholder="请输入用户车牌" />
        </el-form-item>
        <el-form-item label="特征数据" prop="userFaceFeature">
          <el-input v-model="form.userFaceFeature" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="业主ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入业主ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ReviewUserDetail">
import { listReviewUserDetail, getReviewUserDetail, addReviewUserDetail, updateReviewUserDetail, delReviewUserDetail, addSelfReview, approveUserReview } from "@/api/auditUserDetail/reviewUserDetail"
import { listBuildingManage } from "@/api/behindBuilding/buildingManage"
import { listRoomManage } from "@/api/behindRoom/roomManage"
import { listUser } from "@/api/system/user"

const { proxy } = getCurrentInstance()

const reviewUserDetailList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const buildingList = ref([])
const buildingIdToNameMap = ref(new Map())
const roomList = ref([])
const roomIdToNoMap = ref(new Map())
const userList = ref([])
const userIdToNameMap = ref(new Map())
const approvalButtonDisabled = ref({}) // 用于跟踪每个审核按钮的禁用状态

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userBuildingId: null,
    userRoomId: null,
    userCarCode: null,
    userFaceFeature: null,
    userId: null,
    reviewStatus: null
  },
  rules: {
    userBuildingId: [
      { required: true, message: "楼宇ID不能为空", trigger: "blur" }
    ],
    userRoomId: [
      { required: true, message: "房屋ID不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询业主绑定信息审核列表 */
function getList() {
  loading.value = true
  listReviewUserDetail(queryParams.value).then(response => {
    reviewUserDetailList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 获取楼宇列表并建立ID到名称的映射 */
function getBuildingList() {
  return listBuildingManage().then(response => {
    buildingList.value = response.rows || []
    // 建立ID到名称的映射
    buildingIdToNameMap.value = new Map()
    buildingList.value.forEach(building => {
      buildingIdToNameMap.value.set(building.id, building.buildingName)
    })
  })
}

/** 获取房间列表并建立ID到房间号的映射 */
function getRoomList() {
  return listRoomManage().then(response => {
    roomList.value = response.rows || []
    // 建立ID到房间号的映射
    roomIdToNoMap.value = new Map()
    roomList.value.forEach(room => {
      roomIdToNoMap.value.set(room.id, room.roomNo)
    })
  })
}

/** 通过ID获取楼宇名称 */
function getBuildingName(id) {
  if (!id) return ''
  return buildingIdToNameMap.value.get(id) || id
}

/** 通过ID获取房间号 */
function getRoomNo(id) {
  if (!id) return ''
  return roomIdToNoMap.value.get(id) || id
}

/** 获取用户列表并建立ID到名称的映射 */
function getUserList() {
  return listUser().then(response => {
    userList.value = response.rows || []
    // 建立ID到用户名的映射
    userIdToNameMap.value = new Map()
    userList.value.forEach(user => {
      userIdToNameMap.value.set(user.userId, user.nickName || user.userName)
    })
  })
}

/** 通过ID获取用户名称 */
function getUserName(id) {
  if (!id) return ''
  return userIdToNameMap.value.get(id) || id
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 初始化加载数据
Promise.all([
  getBuildingList(),
  getRoomList(),
  getUserList(),
  getList()
])

// 表单重置
function reset() {
  form.value = {
    id: null,
    userBuildingId: null,
    userRoomId: null,
    userCarCode: null,
    userFaceFeature: null,
    userId: null,
    reviewStatus: null
  }
  proxy.resetForm("reviewUserDetailRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加业主绑定信息审核"
}

/** 审核通过按钮操作 */
function handleApproval(row) {
  // 检查按钮是否被禁用
  if (approvalButtonDisabled.value[row.id]) {
    return
  }
  
  const _id = row.id || ids.value
  // 确认审核通过
  proxy.$modal.confirm('是否确认审核通过该申请？').then(function() {
    // 禁用按钮并更改文字
    approvalButtonDisabled.value[row.id] = true
    
    // 设置10秒后重新启用按钮
    setTimeout(() => {
      approvalButtonDisabled.value[row.id] = false
    }, 10000)
    
    // 直接调用后端的审核通过接口，所有业务逻辑由后端处理
    return approveUserReview(_id)
  }).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess(response.msg || "审核通过成功")
      getList()
    } else {
      proxy.$modal.msgError(response.msg || "审核通过失败")
      // 如果失败立即启用按钮
      approvalButtonDisabled.value[row.id] = false
    }
  }).catch(error => {
    console.error('审核过程中发生错误:', error)
    proxy.$modal.msgError("审核失败，请稍后重试")
    // 如果失败立即启用按钮
    approvalButtonDisabled.value[row.id] = false
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["reviewUserDetailRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateReviewUserDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addReviewUserDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除业主绑定信息审核编号为"' + _ids + '"的数据项？').then(function() {
    return delReviewUserDetail(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('auditUserDetail/reviewUserDetail/export', {
    ...queryParams.value
  }, `reviewUserDetail_${new Date().getTime()}.xlsx`)
}

getList()
</script>
